<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends CommonController {
	
	/**
     * [token token验证]
     * @return [type] [json]
     */
	public function __construct(){
		//$this->token();
	}

	/**
     * [gettime 服务器时间]
     * @return [type] [int]
     */
	public function gettime(){
		echo time();
	}
	
	/**
     * [goodsdetail 商品详情图文]
     * @return [type] [json]
     */
    public function detailimage(){
		
		//商品介绍
		$goodsid = I('post.goodsid',0,'intval') ;
        if(!$goodsid) returnApiError(1,'商品id参数错误');
		
		 //商品信息
        $Archives = M("Goods");
        $where['goods_id'] = $goodsid;
        $data = $Archives->field('goods_commonid')->where($where)->find();
        if(!$data) returnApiSuccess('数据为空'); 
		
		$Desc = M("GoodsCommon");
        $desc_where['goods_commonid'] = $data['goods_commonid'];
		$desc_data = $Desc->field('mobile_body')->where($desc_where)->find();
		
		if(!$desc_data){
			$data['mobile_body'] = "";
			returnApiSuccess('数据为空'); 
		}else{
			$mobile_body = unserialize($desc_data['mobile_body']);
			$txtarr = array();
			$i = 0;
			foreach($mobile_body as $k=>$v){
				if($v['type'] == 'image'){
					$txtarr[$i] = $v['value'];
					$i++;
				}
			}
		
			returnApiSuccess('ok',$txtarr); 
		}
	}
	
    /**
     * [goodsdetail 商品详情]
     * @return [type] [json]
     */
    public function goodsdetail(){
        $goodsid = I('post.goodsid',0,'intval') ;
        $uid = I('post.uid',0,'intval') ;
        if(!$goodsid) returnApiError(1,'商品id参数错误');

        //商品信息
        $Archives = M("Goods");
        $where['goods_id'] = $goodsid;
		$where['goods_state'] = 1;
        $data = $Archives->where($where)->find();
        if(!$data) returnApiSuccess('数据为空'); 
        
	$favorites = M('favorites');
	$favorites_info = $favorites->where(array('fav_id'=>"$goodsid",'fav_type'=>'goods','member_id'=>"$uid"))->find();
        if(!empty($favorites_info)){
            $data['is_col'] = 1;
        }else{
            $data['is_col'] = 0;
        }

		//商品相册
		$Images = M("GoodsImages");
        $img_where['goods_commonid'] = $data['goods_commonid'];
		$img_data = $Images->field('goods_image')->where($img_where)->limit(5)->select();
		
		//获取图片完整地址
		foreach($img_data as $k => $v){
			$type = explode("." , $v['goods_image']);
			$img_data[$k]['goods_image'] = 'data/upload/shop/store/goods/'.$data['store_id'].'/'.$type[0].'_1280.'.$type[1];
		}

        if(!$img_data){
            $img_data[0]['goods_image'] = 'data/upload/shop/store/goods/'.$data['store_id'].'/'.$data['goods_image'];
        }
		$data['images'] = $img_data;

        $xianshi = M('p_xianshi_goods');
        $goods_id = $data['goods_id'];
        $xianshi_where['goods_id'] = $goods_id;
        $xianshi_where['state'] = 1;
        $xianshi_where['start_time'] = array('egt',time());
        $xianshi_where['end_time'] = array('elt',time());
        $xianshi_data = $xianshi->where($xianshi_where)->find();
        if($xianshi_data){
            $data['goods_promotion_price'] = $xianshi_data['xianshi_price'];
        }

		//商品介绍
		$Desc = M("GoodsCommon");
        $desc_where['goods_commonid'] = $data['goods_commonid'];
		$desc_data = $Desc->field('mobile_body')->where($desc_where)->find();
		unset ($data['goods_image']);
	    // var_dump($data['mobile_body']);
		if(!$desc_data['mobile_body']){
			$data['mobile_body'] = "";
		}else{
			$mobile_body = unserialize($desc_data['mobile_body']);
			foreach($mobile_body as $v){
				if($v['type'] == 'text'){
					$text .= $v['value'];
				}
			}
			
			$data['mobile_body'] =  !$data['mobile_body'] ? "" : $text;
		}
		
		//商品一条评论
		$Comment = M('EvaluateGoods');
		$where['geval_goodsid'] = $goodsid;
		$com_data = $Comment->field("geval_content,geval_addtime,geval_frommembername,geval_state")->where($where)->find();

		$data['goods_comment'] = array(
              "geval_content" => "",
              "geval_addtime" => "",
              "geval_frommembername" => "",
              "geval_state" => "",
              "member_image" => "",
        );
		$frommembername = $com_data['geval_frommembername'];
		if($com_data){
			//查询评论人头像
			$Member = M('Member');
			$from_where['member_name'] = $frommembername;
			$mem_data = $Member->field('member_avatar')->where($from_where)->find();
			$com_data['member_image'] = $mem_data['member_avatar'];
            $com_data['geval_frommembername'] = $this->half_replace($com_data['geval_frommembername']);
            $com_data['geval_content'] = urldecode($com_data['geval_content']);
			$data['goods_comment'] = $com_data;

		}
	
		//评论统计
		$comCount = $Comment->where($where)->count();
		$data['comment_count'] = $comCount;
		returnApiSuccess('ok',$data); 
        
    }
	

	
    /**
     * [goodsbrowse 浏览历史]
     * @return [type] [json]
     */
    public function goodsbrowse(){
        $uid = I('post.uid',0,'intval');
        if(!$uid)   returnApiError(1,'用户id参数错误');
		
	        //实例化浏览历史
        $Browse = M('GoodsBrowse');
        $goods = C('DB_PREFIX').'goods';
        $browse = C('DB_PREFIX').'goods_browse';
        $data = $Browse->join("$goods ON $browse.goods_id = $goods.goods_id and $browse.member_id = $uid")->limit(20)->select();

        if(!$data){
            returnApiSuccess('数据为空'); 
        }else{
            returnApiSuccess('ok',$data);  
        }
    }
	
	/**
     * [goodscombo 推荐商品]
     * @return [type] [json]
     */
	public function goodscombo(){
		$goodsid = I('post.goodsid',0,'intval');
        if(!$goodsid)   returnApiError(1,'商品id参数错误');
		$Model = M('GoodsCombo');
		$goods = C('DB_PREFIX').'goods';
		$combo = C('DB_PREFIX').'goods_Combo';
        $data = $Model->field("$goods.goods_price,$goods.store_id,$goods.goods_id,$goods.goods_name,$goods.goods_image,$goods.goods_salenum,$goods.goods_state")->join("$goods  ON $combo.combo_goodsid = $goods.goods_id and $combo.goods_id = $goodsid ")->limit(20)->select();
		foreach($data as $k=>$v){
			 $type =explode("." , $v['goods_image']);
             $data[$k]['goods_image'] = 'data/upload/shop/store/goods/'.$v['store_id'].'/'.$type[0].'_240.'.$type[1];
		}
		if(!$data){
			returnArr('数据为空'); 
           // returnApiSuccess('数据为空'); 
        }else{
            returnApiSuccess('ok',$data);  
        }
	}

	/**
     * [comment 商品评论]
     * @return [type] [json]
     */
    public function comment(){
		$goodsid = I('post.goodsid',0,'intval') ; //商品id
		$pindex = I('post.pno',1,'intval') ;     //当前页码
		$psize  = I('post.pgz',10,'intval') ;   //显示条数
		
		if(!$pindex)  $pindex = 1;
		$pfirst = ($pindex - 1) * $psize;
		if(!$goodsid)   returnApiError(1,'商品id参数错误');
		
		$Model = M('EvaluateGoods');
		$member = C('DB_PREFIX').'member';
		$comment = C('DB_PREFIX').'evaluate_goods';
		$data = $Model->field("$member.member_avatar,$member.member_name,$member.member_truename,$comment.geval_content,$comment.geval_addtime,$comment.geval_frommembername,$comment.geval_state")->join("$member ON $comment.geval_frommemberid = $member.member_id and $comment.geval_goodsid = $goodsid")->limit($pfirst .','.$psize)->select();

		if(!$data){
            returnArr('数据为空'); 
        }
        foreach($data as $k=>$v){
            $data[$k]['geval_content'] = urldecode($data[$k]['geval_content']);
            $data[$k]['member_name'] = $this->half_replace($data[$k]['member_name']);
            $data[$k]['geval_frommembername'] = $this->half_replace($data[$k]['geval_frommembername']);
        }
        returnApiSuccess('ok',$data);

	}

    function half_replace($str){
        $len = strlen($str)/2;
        return substr_replace($str,str_repeat('*',$len),ceil(($len)/2),$len);
    }


    /**
     * [goodslist 商品列表]
     * @return [type] [json]
     */
    public function goodslist(){
    	$typeid = I('post.type_id',0,'intval') ; //商品分类id
    	$pindex = I('post.pno',1,'intval') ;     //当前页码
		$psize  = I('post.pgz',10,'intval') ;   //显示条数
        $uid = I('post.uid',0,'intval');        //用户id
		if(!$pindex)  $pindex = 1;
		
    	//分页计算
		$pfirst = ($pindex - 1) * $psize;

		//商品类型参数判断
    	if(!$typeid)  returnApiError(1,'分类id参数错误');

        //查询条件
		$where['gc_id_1'] = $typeid;
		$where['goods_state'] = 1;

		//实例化查询
    	$Archives = M("goods");
		$data = $Archives->field('goods_id,goods_name,store_id,goods_total,gc_id_1,goods_price,goods_promotion_price,goods_promotion_type,goods_image,company,goods_commend,is_appoint')->where($where)->limit($pfirst .','.$psize)->select();

        $xianshi = M('p_xianshi_goods');

        //获取图片地址
        foreach($data as $k => $v){

            //判断限时折扣
            $goods_id = $v['goods_id'];

            $xianshi_where['goods_id'] = $goods_id;
            $xianshi_where['state'] = 1;
            $xianshi_where['start_time'] = array('egt',time());
            $xianshi_where['end_time'] = array('elt',time());
            $xianshi_data = $xianshi->where($xianshi_where)->find();
            if($xianshi_data){
                $data[$k]['goods_promotion_price'] = $xianshi_data['xianshi_price'];
            }
            $type =explode("." , $v['goods_image']);
            $data[$k]['goods_image'] = 'data/upload/shop/store/goods/'.$v['store_id'].'/'.$type[0].'_240.'.$type[1];
        }

        //商品购买记录
        if($uid){
            $arr = array();
            $Cart = M("Cart");
            $where['buyer_id'] = $uid;
            $shopcart = $Cart->where($where)->select();
            if($shopcart){
                foreach($data as $k=>$v){
                    foreach($shopcart as $k2=>$v2){
                        if($v['id'] == $v2['goodsid']){
                            $arr[$k]['goods_id'] = $v['goods_id'];
                            $arr[$k]['goods_name'] = $v['goods_name'];
                            $arr[$k]['gc_id_1'] = $v['gc_id_1'];
                            $arr[$k]['goods_promotion_price'] = $v['goods_promotion_price'];
                            $arr[$k]['goods_price'] = $v['goods_price'];
                            $arr[$k]['goods_promotion_type'] = $v['goods_promotion_type'];
                            $arr[$k]['goods_image'] = $v['goods_image'];
                            $arr[$k]['goods_total'] = $v2['goods_num'];
                            $arr[$k]['store_id'] = $v['store_id'];

                        }
                    }
                }
                $data = $arr;
            }
        }

		if(!$data){
             returnArr('数据为空'); 
		}else{
			 returnApiSuccess('ok',$data); 
		}
		
    }
	
    /**
     * [category 分类]
     * @return [type] [json]
     */
    public function category(){
        //查询条件
        $where['gc_parent_id'] = 0;  //一级分类

        //实例化查询
        $Arctype = M("goods_class");
        $data = $Arctype->field('gc_id,gc_name')->where($where)->select();
        if(!$data){
            returnApiSuccess('数据为空'); 
        }else{
            returnApiSuccess('ok',$data);  
        }

    }

    /**
     * [cart 购物车列表]
     * @return [type] [json]
     */
    public function shopcart(){
        //接收用户id参数
        $uid = I('post.uid',0,'intval');
        if(!$uid){
            returnApiError(1,'用户id参数错误');
        }

        //购物车实例化查询
        $Cart = M("Cart");
        $where['buyer_id'] = $uid;
        $data = $Cart->where($where)->select();
        if(!$data){
            returnArr('数据为空'); 
        }
        $cart_arr = array();

        //商品实例化查询
        $Archives = M('Goods');
        foreach($data as $k=>$v){
            $goodsid = $v['goods_id'];
            $goodsnum = $v['goods_num'];
            $goods_where['goods_id'] = $goodsid;
            $goods = $Archives->where($goods_where)->find();
            $cart_arr[$k]['goods_name'] = $goods['goods_name'];
            $cart_arr[$k]['goods_price'] = $goods['goods_promotion_price'];
            $cart_arr[$k]['goods_id'] = $goodsid;
            $cart_arr[$k]['goods_num'] = $goodsnum;
		
			//获取图片地址
			$type =explode("." , $v['goods_image']);
            $cart_arr[$k]['goods_image'] = 'data/upload/shop/store/goods/'.$v['store_id'].'/'.$type[0].'_240.'.$type[1];
        
        }
      
        $data = $cart_arr;
        returnApiSuccess('ok',$data);  
    }

    /**
     * [delcart 清空购物车]
     * @return [type] [json]
     */
    public function delcart(){
        //接收用户id参数
        $uid = I('post.uid',0,'intval');
        if(!$uid){
            returnApiError(1,'用户id参数错误');
        }

        // 删除用户购物车数据
        $Cart = M("Cart");
        $data =  $Cart->where("buyer_id = $uid")->delete();
        returnApiSuccess('ok');  
        
    }

    /**
     * [addcart 添加购物车]
     * @return [type] [json]
     */
    public function addcart(){
        $Goods = M("Goods");
        $Cart = M("Cart");
        $data = $_POST['param'];
		$data = json_decode($data,true);
        $uid = $data['uid'];
        $list = $data['list'];
        $where['buyer_id'] = $uid;
		if(!$data) returnApiError(1,'param参数错误');
        if(!$uid) returnApiError(1,'用户id参数错误');
        if(!$list) {
            $data =  $Cart->where($where)->delete();
            returnApiSuccess('ok');  
        };


        $Cart->where($where)->delete(); //清除之前购物车数据

        foreach($list as $k=>$v) {
            $where['goods_id'] =  $v['goodsid'];
            $result = $Goods->where($where)->find();
            if(!$result) continue;
            $where['goods_id'] = $v['goodsid'];
            $data['buyer_id'] = $uid;
            $data['goods_num'] = $v['number'];
            $data['goods_name'] = $result['goods_name'];
            $data['goods_price'] = $result['goods_promotion_price'];
            $data['goods_image'] = $result['goods_image'];
            $data['store_id'] = $result['store_id'];
            $data['goods_id'] = $v['goodsid'];
            $Cart->add($data);
        }

        returnApiSuccess('ok');  
    }

    /**
     * 商品搜索
     */
    public function searchgoods(){
        $status = I('post.status');
        $array = array();
        switch($status){
            case 1 :
                $salenum =  true ;
                break;
            case 2:
                $click =  true;
                break;
            case 3:
                $price = true;
                break;
            case 4:
                $price2 = true;
        }

        $pindex = I('post.pno',1,'intval') ;
        $psize  = I('post.pgz',10,'intval') ;
        if($price){
            $array['goods_promotion_price'] = 'desc';
        }
        if($price2){
            $array['goods_promotion_price'] = 'asc';
        }
        if($click){
            $array['goods_click'] = 'desc';
        }
        if($salenum){
            $array['goods_salenum'] = 'desc';
        }

       /* $price = $price ? 'desc' : 'asc';
        $click = $click ? 'desc' : 'asc';
        $salenum = $salenum ? 'desc' : 'asc';
        */

        if(!$pindex)  $pindex = 1;
        $pfirst = ($pindex - 1) * $psize;
        if (I('post.keyword') != '') {
            $condition['goods_name|goods_jingle'] = array('like', '%' . $_POST['keyword'] . '%');
        }

        $Model = M('goods');
        $condition['goods_state'] = 1;
        $field = "goods_id,goods_name,store_id,goods_commend,evaluation_count,is_appoint,goods_price,goods_promotion_price,goods_promotion_type,goods_image,goods_salenum,goods_click,company";
        $list = $Model->field($field)->where($condition)->limit($pfirst .','.$psize)->order($array)->select();
        //$list = $Model->field($field)->where($condition)->limit($pfirst .','.$psize)->order(array( 'goods_price' => $price, 'goods_click' => $click,'goods_salenum'=> $salenum))->select();
        if($list){
            $xianshi = M('p_xianshi_goods');
            foreach($list as $k=>$v){
                //判断限时折扣
                $goods_id = $v['goods_id'];
                $xianshi_where['goods_id'] = $goods_id;
                $xianshi_where['state'] = 1;
                $xianshi_where['start_time'] = array('egt',time());
                $xianshi_where['end_time'] = array('elt',time());
                $xianshi_data = $xianshi->where($xianshi_where)->find();
                if($xianshi_data){
                    $data[$k]['goods_promotion_price'] = $xianshi_data['xianshi_price'];
                }
            }
            returnApiSuccess('ok',$list);
        }
        returnArr('ok');

    }

//    public function indexadv(){
//
//        $adv = M('adv');
//        $data = $adv->field('adv_title,adv_content,adv_start_date,adv_end_date')->where("ap_id = 1050")->select();
//    
//        foreach($data as $k=>$v){
//            $data[$k]['adv_content'] = unserialize($data[$k]['adv_content']);
//
//            $data[$k]['img_url'] = SHOP_SITE_URL.'/data/upload/shop/adv/'.$data[$k]['adv_content']['adv_pic'];
//            $data[$k]['link'] = $data[$k]['adv_content']['adv_pic_url'];
//            unset($data[$k]['adv_content']);
//            if($data[$k]['adv_start_date'] > time()){
//                unset($data[$k]);
//            }
//            if($data[$k]['adv_end_date'] < time()){
//                unset($data[$k]);
//            }
//            unset($data[$k]['adv_start_date']);
//            unset($data[$k]['adv_end_date']);
//
//
//        }
//        returnApiSuccess('ok',$data);
//
//    }
    public function indexadv(){
        $adv = M('adv');
        $where["ap_id"] = array("in","1050,1052,1053,1054");
        $data = $adv->field('adv_id,adv_title,ap_id,adv_content,adv_start_date,adv_end_date')->where($where)->order(array("adv_id"=>"asc"))->select();
        $advf = $advt = $advth = array();
        if(!$data)returnApiError(1,'数据为空');
        foreach($data as $k=>$v){
            if($v['adv_start_date'] > time()){
                unset($data[$k]);
            }
            if($v['adv_end_date'] < time()){
                unset($data[$k]);
            }
            if($data[$k]['adv_content']){
             $imgar = unserialize($v['adv_content']);
             $img = SHOP_SITE_URL.'/data/upload/shop/adv/'.$imgar['adv_pic'];
            }
            $ndata["img_url"] = $img;
            $ndata["adv_id"] = $data[$k]["adv_id"];
            $ndata['adv_pic_url'] = $imgar["adv_pic_url"];
              if($data[$k]["ap_id"]==1050){
                 $ndata["title"] ="首页轮播图";
                 $datas["banner"][] = $ndata;
              }
            if($data[$k]["ap_id"]==1052){
                 $ndata["title"] ="720*262图片广告位";
                  if($v["adv_title"]=="广告4-底部优食优选"){
                     $tmp[0] = $ndata;
                     continue;
                 }
                 $datas["adver_1"][] = $ndata;
                 
              }
              if($data[$k]["ap_id"]==1053){
                  $ndata["title"] ="350*220图片广告位";
                  $datas["adver_2"][] = $ndata;
              }
              if($data[$k]["ap_id"]==1054){
                    $ndata["title"] ="288*442图片广告位";
                    array_push($advt, $ndata);
              }
        }
        $i=1; $j=0;
       foreach ($datas["adver_2"] as $k => $vl) {
           $is = false;
            if ($i == 1) {
                $tmp[1] = $vl;
            } else {
                $tmp[] = $vl;
                if ($i % 2 == 0) {
                    if($new = $advt[$j]){
                        $tmp[] = $advt[$j];
                        $j++;
                    }
                }
            }
            $i++;
        }
         $datas["adver_2"]=$tmp;
        returnApiSuccess('ok',$datas);
    }
     public function iosindexadv(){
        $adv = M('adv');
        $where["ap_id"] = array("in","1050,1055,1056,1057");
        $data = $adv->field('adv_id,adv_title,ap_id,adv_content,adv_start_date,adv_end_date')->where($where)->order(array("adv_id"=>"asc"))->select();
        $advf = $advt = $advth = array();
        if(!$data)returnApiError(1,'数据为空');
        foreach($data as $k=>$v){
            if($v['adv_start_date'] > time()){
                unset($data[$k]);
            }
            if($v['adv_end_date'] < time()){
                unset($data[$k]);
            }
            if($data[$k]['adv_content']){
             $imgar = unserialize($v['adv_content']);
             $img = SHOP_SITE_URL.'/data/upload/shop/adv/'.$imgar['adv_pic'];
            }
            $ndata["img_url"] = $img;
            $ndata["adv_id"] = $data[$k]["adv_id"];
            $ndata['adv_pic_url'] = $imgar["adv_pic_url"];
              if($data[$k]["ap_id"]==1050){
                 $ndata["title"] ="首页轮播图";
                 $datas["banner"][] = $ndata;
              }
            if($data[$k]["ap_id"]==1055){
                 $ndata["title"] ="640*300图片广告位";
                 if($v["adv_title"]=="广告4-底部优食优选"){
                     $tmp[0] = $ndata;
                     continue;
                 }
                 $datas["adver_1"][] = $ndata;
              }
              if($data[$k]["ap_id"]==1056){
                  $ndata["title"] ="525*330图片广告位";
                  $datas["adver_2"][] = $ndata;
              }
              if($data[$k]["ap_id"]==1057){
                    $ndata["title"] ="432*663图片广告位";
                    array_push($advt, $ndata);
              }
        }
        $i=1; $j=0;
       foreach ($datas["adver_2"] as $k => $vl) {
           $is = false;
            if ($i == 1) {
                $tmp[1] = $vl;
            } else {
                $tmp[] = $vl;
                if ($i % 2 == 0) {
                    if($new = $advt[$j]){
                        $tmp[] = $advt[$j];
                        $j++;
                    }
                }
            }
            $i++;
        }
         $datas["adver_2"]=$tmp;
        returnApiSuccess('ok',$datas);
    }
    /**
     * 我的订单商品评论
     */
    public function myevalevaluate(){
        $uid = I('post.uid',0,'intval');
        $goodsid = I('post.goodsid',0,'intval');
        if(!$uid) returnApiError(1,'uid参数错误');
        if(!$goodsid) returnApiError(1,'goodsid参数错误');
        $evaluate_goods = M('evaluate_goods');
        $where['geval_frommembername'] = $uid;
        $where['geval_goodsid'] = $goodsid;
        $data = $evaluate_goods->where($where)->select();
        if($data){
            foreach($data as $k=>$v){
                $data[$k]['geval_content'] = urldecode($data[$k]['geval_content']);
            }
            returnApiSuccess('ok',$data);
        }
        returnArr('数据为空');
    }

    /**
     * 商品分享
     */
    public function goodsshare(){
        $goods_id = I('post.goods_id');
        if(!$goods_id) returnApiError(1,'缺少商品id参数');
        $url = SHOP_SITE_URL.'/wap/tmpl/product_detail.html?goods_id='.$goods_id;
        returnApiSuccess('ok',$url);
    }



}